package com.sanjishu.enterlab.electricity.sale.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SmsService {

    private static final Logger log = LoggerFactory.getLogger(SmsService.class);

    @Value("${message.accessId}")
    private String accessId;
    @Value("${message.accessKey}")
    private String accessKey;
    @Value("${message.sms.signName}")
    private String signName;

    //产品名称:云通信短信API产品,开发者无需替换
    private String product = "Dysmsapi";
    //产品域名,开发者无需替换
    private String domain = "dysmsapi.aliyuncs.com";

    @Async
    public void sendMessage(String cellphone, String templateCode, Map<String, String> params) {
        try {
            sendSyncMessage(cellphone, templateCode, params);
        } catch (Exception e) {
            log.error("", e);
        }
    }

    public SendSmsResponse sendSyncMessage(String cellphone, String templateCode, Map<String, String> params) throws Exception {
        if (templateCode == null){
            return null;
        }

        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessId, accessKey);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(cellphone);
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        if(params != null){
            ObjectMapper mapper = new ObjectMapper();
            request.setTemplateParam(mapper.writeValueAsString(params));
        }
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
        log.info("{} {} {} {} {} {}", signName, cellphone, templateCode, sendSmsResponse.getCode(), sendSmsResponse.getMessage(), sendSmsResponse.getRequestId());
        return sendSmsResponse;
    }

}
